package com.metis.document.parse.dialog.pipeline.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.metis.document.parse.dialog.constant.DesensitizationRegexEnum;
import com.metis.document.parse.dialog.pipeline.TextPostProcess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DesensitizeTextPostProcess implements TextPostProcess {
    @Override
    public String process(@NotNull String input) {
        Collection<DesensitizationRegexEnum> desensitizationRegexEnums = List.of(DesensitizationRegexEnum.values());
        Map<DesensitizationRegexEnum, Pattern> patterns = new HashMap<>();
        for (DesensitizationRegexEnum regexEnum : desensitizationRegexEnums) {
            patterns.put(regexEnum, Pattern.compile(regexEnum.getRegex()));
        }
        for (Map.Entry<DesensitizationRegexEnum, Pattern> entry : patterns.entrySet()) {
            DesensitizationRegexEnum regexEnum = entry.getKey();
            Matcher matcher = entry.getValue().matcher(input);
            //如果能够匹配则替换为同等长度的*
            if (matcher.find()) {
                String matchedStr = matcher.group();
                String originNew = input.replaceAll(regexEnum.getRegex(), "");
                log.info("脱敏策略: {} , 原始值: {} , 脱敏值: {}", regexEnum.getName(), input, matchedStr);
                input = originNew;
                break;
            }
        }
        return input;
    }
}
